package me.zhyx.music.compoent;

import lombok.extern.slf4j.Slf4j;
import me.zhyx.music.init.TaskQueue;
import me.zhyx.music.model.Music;
import me.zhyx.music.model.Proxy_ip;
import me.zhyx.music.service.MusicService;
import me.zhyx.music.service.ProxyService;
import me.zhyx.music.utils.HttpClientUtils;
import org.apache.http.HttpHost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @Auther: yssq
 * @Date: 2019/3/14 14:03
 * @Description:
 */
@Component
@Slf4j
public class JobRelease {

    @Autowired
    MusicService musicService;

    @Autowired
    ProxyService proxyService;

    @Scheduled(cron = "0/1 * * * * ?")
    public void findExceptionUrl() {
        if (TaskQueue.url.isEmpty()) {
            TaskQueue.url.addAll(musicService.selectExceptionUrl());
        }
    }

    @Scheduled(cron = "0/1 * * * * ?")
    public void saveProduct() {
        while (!TaskQueue.product.isEmpty()) {
            Music music = TaskQueue.product.poll();
            try {
                log.info("Save Music start!");
                musicService.saveMusic(music);
                log.info("Save Music end!");
                musicService.updateMusic(music.getSourceAddress(), 1);
            } catch (Exception e) {
                log.error("Exception {}", e.getCause());
            }
        }

    }

    //    @Scheduled(cron = "0 */1 * * * ?")
    public void saveException() {
        try {
            while (!TaskQueue.productException.isEmpty()) {
                musicService.saveException(TaskQueue.productException.poll());
            }
            Proxy_ip proxyIp = TaskQueue.proxy_ips.poll();
            HttpClientUtils.requestConfig(new HttpHost(proxyIp.getIp(), proxyIp.getPort(), proxyIp.getType()));
        } catch (Exception e) {
            log.error("Exception {}", e.getCause());
        }
    }

    @Scheduled(cron = "0 * * * * ?")
    public void updateProxy() {
        if (TaskQueue.proxy_ips.isEmpty()) {
            TaskQueue.proxy_ips.addAll(proxyService.selectProxy());
        }
    }

}
